# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import _, api, fields, models
from odoo.exceptions import UserError


class StockReturnPickingEx(models.TransientModel):
    _inherit = "stock.return.picking"
    create_mo_req = fields.Boolean(string="Reconstruction of MO material requirements", default=True)
    picking_type_code = fields.Selection(related="picking_id.picking_type_id.code")

    def _create_returns(self):
        # Prevent copy of the carrier and carrier price when generating return picking
        # (we have no integration of returns for now)

        new_picking, pick_type_id = super()._create_returns()
        for return_line in self.product_return_moves:
            if return_line.move_id:
                if self.create_mo_req:
                    oldmove = return_line.move_id
                    m = oldmove.copy()
                    if m.ori_product_uom_qty > 0:  # 20240921
                        m.write({
                            'quantity': m.ori_product_qty,
                            'quantity_done': m.ori_product_qty,
                            'product_id': m.ori_product_id,
                            'product_uom': m.ori_product_uom,
                            'product_uom_qty': m.ori_product_uom_qty,
                            'unit_factor': m.ori_unit_factor,
                            'partner_id': False,
                            'picking_id': False,
                            'alt_material_id': False,
                            'alt_material_uom_id': False,
                            'alt_quan_bom': False,
                            'alt_quan_done': False
                        })
                    oldmove.write({
                        "return_uom_qty": return_line.quantity
                    })
        picking = self.env['stock.picking'].browse(new_picking)
        for m in picking.move_ids_mrp_operation:
            m.write({"location_dest_id": picking.location_dest_id})
        if self.picking_type_code == 'wmissue':
            picking.action_confirm()
            picking.action_assign()
            picking.button_validate()
        return new_picking, pick_type_id
    # @api.model
    # def default_get(self, default_fields):
    #     res = super(StockReturnPicking, self).default_get(default_fields)
    #     for i, k, vals in res.get('product_return_moves', []):
    #         vals.update({'to_refund': True})
    #     return res
    #
    # def _prepare_move_default_values(self, return_line, new_picking):
    #     vals = super(StockReturnPicking, self)._prepare_move_default_values(return_line, new_picking)
    #     if return_line.to_refund:
    #         vals['to_refund'] = True
    #     return vals

#
# class StockReturnPickingLineEx(models.TransientModel):
#     _inherit = "stock.return.picking.line"
#
#     to_recreate_req = fields.Boolean(string="重建物料需求", default=True,
#         help='触发创建MO需求')
